package cn.oniokey.waterDetection.controller;

import cn.oniokey.waterDetection.domain.Water;
import cn.oniokey.waterDetection.service.WaterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/water")
public class GetWaterByIdController {
    final
    WaterService waterService;

    public GetWaterByIdController(WaterService waterService) {
        this.waterService = waterService;
    }

    @PostMapping("/getWaterById")
    public Map<String, Object> getWaterById(@RequestBody(required = false) Map<String, Object> requestParams) {

        // 默认 pageNum=1 pageSize=10
        int pageNum = 1;
        int pageSize = 10;
        String clientId = null;

        if (requestParams != null) {
            pageNum = Integer.parseInt((String) requestParams.getOrDefault("pageNum", "1"));
            pageSize = Integer.parseInt((String) requestParams.getOrDefault("pageSize", "10"));
            // 将传入的 clientId 封装到字符串中
            clientId = (String) requestParams.get("clientId");
        }
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        // 调用查询方法将数据封装到List中
        List<Water> waterList = waterService.getWaterById(clientId);
        // 封装分页信息
        PageInfo<Water> pageInfo = new PageInfo<>(waterList);
        // 封装响应数据
        Map<String, Object> response = new HashMap<>();
        // 分页信息的数据
        response.put("data", pageInfo.getList());
        // 分页信息的数据总数
        response.put("totalRecords", pageInfo.getTotal());
        // 分页信息的页码
        response.put("currentPage", pageInfo.getPageNum());
        // 分页信息的总页码
        response.put("recordsPerPage", pageInfo.getPageSize());

        return response;
    }
}
